package com.svpino.netflix.parsers;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.svpino.netflix.ProxyImpl;
import com.svpino.netflix.model.Title;


public class TitleParser extends ListParser<Title> {

	public TitleParser(ProxyImpl connection) {
		super(connection);
	}

	@Override
	public List<Title> list(Element... elements) {
		Element element = elements[0];
		
		try {
			List<Title> list = new ArrayList<Title>();
			
			XPathFactory factory = XPathFactory.newInstance();
			XPath xPath = factory.newXPath();
			XPathExpression mpaaRatingsXPathExpression = xPath.compile("./category[@scheme='http://api.netflix.com/categories/mpaa_ratings']");

			NodeList nodeList = element.getElementsByTagName("catalog_title");
			for (int i = 0; i < nodeList.getLength(); i++) {
				Element catalogTitleElement = (Element) nodeList.item(i);
				
				String id = ((Element) catalogTitleElement.getElementsByTagName("id").item(0)).getTextContent();
				Element titleElement = (Element) catalogTitleElement.getElementsByTagName("title").item(0);

				String shortTitle = titleElement.getAttribute("short");
				String regularTitle = titleElement.getAttribute("regular");

				Element releaseYearElement = (Element) catalogTitleElement.getElementsByTagName("release_year").item(0);
				int releaseYear = Integer.parseInt(releaseYearElement.getTextContent());

				Element ratingElement = (Element) catalogTitleElement.getElementsByTagName("average_rating").item(0);
				float rating = Float.parseFloat(ratingElement.getTextContent());

				Element mpaaRatingElement = (Element) mpaaRatingsXPathExpression.evaluate(catalogTitleElement, XPathConstants.NODE);
				String mpaaRating = mpaaRatingElement != null ? mpaaRatingElement.getAttribute("term") : "";

				Integer runtime = null;
				NodeList runtimeNodeList = catalogTitleElement.getElementsByTagName("runtime");
				if (runtimeNodeList.getLength() != 0) {
					runtime = Integer.parseInt(runtimeNodeList.item(0).getTextContent());
				}
				
				Title catalogTitle = new Title(
						getConnection(), 
						id, 
						regularTitle, 
						shortTitle, 
						releaseYear, 
						rating, 
						runtime,
						mpaaRating,
						catalogTitleElement);
				
				list.add(catalogTitle);
			}

			return list;

		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}
